package photogcalc.util;

/** Util class for some mathematics calculations.
 *  This is and should be freely available for anyone as a Public Domain.
 *
 * @author Antti Okkonen
 * @version 2010-02-10
 */
public class MathUtil {

    public static final int ITERATIONS = 5;
    /** PI = 3.14159265 */
    public static final double PI = 3.14159265;

    /** Calculates x<sup>y</sup>
    @param x base
    @param y exponent
    @return x<sup>y</sup>
     */
    public static double pow(double x, double y) {
        /* break the recursion */
        if (y == 0) {
            //System.out.print("1 ");
            return 1;
        }
        else {
            //System.out.print(x+" * ");
            return x * pow(x, y - 1);
        }
    }

    public static double nonRecursivePower(double x, double y) {
        for (int i = 0; i < y; i++) {
            x *= x;
        }

        return x;
    }

    /** Calculates arctan with CORDIC algorithm. 
     *  Find more information from http://www.convict.lu/Jeunes/Math/arctan.htm
     * 
     *  @param x
     *  @return Angle in radians. 
     */
    public static double cordic_atan(double x) {
        boolean over45degrees = (x > 1) ? true : false;
        double sum = x = (over45degrees) ? 1 / x : x;

        double tmp;
        for (int i = 1; i < MathUtil.ITERATIONS; i++) {
            int exp = i * 2 + 1;
            tmp = MathUtil.nonRecursivePower(x, exp) / (exp);

            /* even */
            if (i % 2 != 0) {
                sum += -tmp;
            }
            /* odd */ else {
                sum += tmp;
            }
        }

        // TODO: Check constant 1.63 value. It's good approximation.
        return (over45degrees) ? 1.63 - sum : sum;
    }
}
